<template>
  <div class="dashboard">
    <a-spin :spinning="loading">
      <a-page-header title="数据总览" sub-title="实时监控平台数据">
        <template #extra>
          <a-range-picker v-model:value="dateRange" @change="handleDateChange" />
        </template>
      </a-page-header>
    
    <!-- 统计卡片 -->
    <a-row :gutter="[16, 16]" class="stats-row">
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card card-shadow">
          <a-statistic
            title="总用户数"
            :value="stats.totalUsers"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix>
              <user-outlined />
            </template>
          </a-statistic>
          <div class="stat-footer">
            <span>较昨日 
              <a-tag :color="stats.userGrowthRate >= 0 ? 'success' : 'error'">
                {{ stats.userGrowthRate >= 0 ? '+' : '' }}{{ stats.userGrowthRate.toFixed(2) }}%
              </a-tag>
            </span>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card card-shadow">
          <a-statistic
            title="教员总数"
            :value="stats.totalTeachers"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <team-outlined />
            </template>
          </a-statistic>
          <div class="stat-footer">
            <span>较昨日 
              <a-tag :color="stats.teacherGrowthRate >= 0 ? 'success' : 'error'">
                {{ stats.teacherGrowthRate >= 0 ? '+' : '' }}{{ stats.teacherGrowthRate.toFixed(2) }}%
              </a-tag>
            </span>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card card-shadow">
          <a-statistic
            title="订单总数"
            :value="stats.totalOrders"
            :value-style="{ color: '#cf1322' }"
          >
            <template #prefix>
              <shopping-outlined />
            </template>
          </a-statistic>
          <div class="stat-footer">
            <span>较昨日 
              <a-tag :color="stats.orderGrowthRate >= 0 ? 'success' : 'error'">
                {{ stats.orderGrowthRate >= 0 ? '+' : '' }}{{ stats.orderGrowthRate.toFixed(2) }}%
              </a-tag>
            </span>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card card-shadow">
          <a-statistic
            title="今日收入"
            :value="stats.todayIncome"
            prefix="¥"
            :precision="2"
            :value-style="{ color: '#faad14' }"
          >
            <template #prefix>
              <dollar-outlined />
            </template>
          </a-statistic>
          <div class="stat-footer">
            <span>较昨日 
              <a-tag :color="stats.incomeGrowthRate >= 0 ? 'success' : 'error'">
                {{ stats.incomeGrowthRate >= 0 ? '+' : '' }}{{ stats.incomeGrowthRate.toFixed(2) }}%
              </a-tag>
            </span>
          </div>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 图表区域 -->
    <a-row :gutter="[16, 16]" class="charts-row">
      <a-col :xs="24" :lg="16">
        <a-card title="用户增长趋势" class="card-shadow">
          <v-chart :option="userTrendOption" style="height: 400px;" />
        </a-card>
      </a-col>
      
      <a-col :xs="24" :lg="8">
        <a-card title="订单状态分布" class="card-shadow">
          <v-chart :option="orderStatusOption" style="height: 400px;" />
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 待处理事项 -->
    <a-row :gutter="[16, 16]" class="pending-row">
      <a-col :xs="24" :lg="12">
        <a-card title="待审核教员" class="card-shadow">
          <template #extra>
            <a href="#">查看全部</a>
          </template>
          <a-list
            :data-source="pendingTeachers"
            size="small"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :src="item.avatar" />
                  </template>
                  <template #title>
                    {{ item.name }}
                  </template>
                  <template #description>
                    {{ item.school }} - {{ item.education }}
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button type="primary" size="small">审核</a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :lg="12">
        <a-card title="待处理反馈" class="card-shadow">
          <template #extra>
            <a href="#">查看全部</a>
          </template>
          <a-list
            :data-source="pendingFeedback"
            size="small"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    {{ item.title }}
                  </template>
                  <template #description>
                    {{ item.content }}
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-tag :color="item.priority === 'high' ? 'red' : 'default'">
                    {{ item.priority }}
                  </a-tag>
                  <a-button type="link" size="small">处理</a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { UserOutlined, TeamOutlined, ShoppingOutlined, DollarOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { getStatisticsOverview, getUserTrend, getOrderStats } from '@/api/statistics'

use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const dateRange = ref([])
const loading = ref(false)

const stats = reactive({
  totalUsers: 0,
  totalTeachers: 0,
  totalOrders: 0,
  todayIncome: 0,
  userGrowthRate: 0,
  teacherGrowthRate: 0,
  orderGrowthRate: 0,
  incomeGrowthRate: 0
})

const pendingTeachers = ref([
  {
    id: 1,
    name: '张老师',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=teacher1',
    school: '北京大学',
    education: '硕士'
  },
  {
    id: 2,
    name: '李老师',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=teacher2',
    school: '清华大学',
    education: '博士'
  },
  {
    id: 3,
    name: '王老师',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=teacher3',
    school: '复旦大学',
    education: '本科'
  }
])

const pendingFeedback = ref([
  {
    id: 1,
    title: '订单退款问题',
    content: '用户反馈订单退款迟迟未到账',
    priority: 'high'
  },
  {
    id: 2,
    title: '教员信息错误',
    content: '教员资料显示有误',
    priority: 'normal'
  },
  {
    id: 3,
    title: '系统功能建议',
    content: '希望增加在线支付功能',
    priority: 'low'
  }
])

// 用户增长趋势图配置
const userTrendOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['家长', '教员']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '家长',
      type: 'line',
      data: [],
      smooth: true,
      itemStyle: { color: '#1890ff' }
    },
    {
      name: '教员',
      type: 'line',
      data: [],
      smooth: true,
      itemStyle: { color: '#52c41a' }
    }
  ]
})

// 订单状态分布图配置
const orderStatusOption = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

const handleDateChange = (dates) => {
  console.log('日期范围:', dates)
  // 这里可以根据日期范围重新加载数据
  loadStatistics()
}

// 加载概览数据
const loadOverview = async () => {
  try {
    const res = await getStatisticsOverview()
    if (res.code === 200 && res.data) {
      Object.assign(stats, res.data)
    }
  } catch (error) {
    console.error('加载概览数据失败:', error)
    message.error('加载概览数据失败')
  }
}

// 加载用户趋势数据
const loadUserTrend = async () => {
  try {
    const res = await getUserTrend({ days: 7 })
    if (res.code === 200 && res.data) {
      userTrendOption.value.xAxis.data = res.data.dates
      userTrendOption.value.series[0].data = res.data.parentData
      userTrendOption.value.series[1].data = res.data.teacherData
    }
  } catch (error) {
    console.error('加载用户趋势数据失败:', error)
    message.error('加载用户趋势数据失败')
  }
}

// 加载订单统计数据
const loadOrderStats = async () => {
  try {
    const res = await getOrderStats()
    if (res.code === 200 && res.data && res.data.statusItems) {
      const colors = {
        '待支付': '#faad14',
        '进行中': '#1890ff',
        '已完成': '#52c41a',
        '已取消': '#d9d9d9'
      }
      orderStatusOption.value.series[0].data = res.data.statusItems.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: { color: colors[item.name] || '#999' }
      }))
    }
  } catch (error) {
    console.error('加载订单统计数据失败:', error)
    message.error('加载订单统计数据失败')
  }
}

// 加载所有统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadOverview(),
      loadUserTrend(),
      loadOrderStats()
    ])
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadStatistics()
})
</script>

<style lang="scss" scoped>
.dashboard {
  .stats-row {
    margin-top: 24px;
  }
  
  .stat-card {
    .stat-footer {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.45);
    }
  }
  
  .charts-row {
    margin-top: 16px;
  }
  
  .pending-row {
    margin-top: 16px;
  }
}
</style>

